<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Exceptions\ApiException;
use App\Format\GridFormat;
use App\Models\Grid;

class GridService
{
    public function getGrids()
    {
        $grids = Grid::query()->get()->toArray();
        $result = [
            'level_first' => [],
            'level_frist' => [], // 临时处理 小程序没改
            'level_second' => [],
            'level_third' => [],
        ];
        foreach ($grids as $key => $value) {
            if ($value['type'] == 1) {
                array_push($result['level_first'], $value);
                array_push($result['level_frist'], $value);
            }
            if ($value['type'] == 2) {
                array_push($result['level_second'], $value);
            }
            if ($value['type'] == 3) {
                array_push($result['level_third'], $value);
            }
        }
        return $result;
    }

    public function getAdminList()
    {
        return Grid::query()->get()->toArray();
    }

    public function create(GridFormat $gridFormat)
    {
        Grid::query()->create($gridFormat->toArrayNotNull());
        adminLog(new Grid(), AdminActionTypeEnum::CREATE, '创建网格');
        return true;
    }

    public function update(GridFormat $gridFormat)
    {
        if (empty($gridFormat->getId())) {
            throw new ApiException('缺少参数', 1);
        }
        $grid = Grid::query()->find($gridFormat->getId());
        $data = $gridFormat->toArrayNotNull();
        unset($data['id']);
        $grid->update($data);
        adminLog($grid, AdminActionTypeEnum::UPDATE, '修改网格');
        return true;
    }

    public function delete(int $id)
    {
        $grid = Grid::query()->find($id);
        if (empty($grid)) {
            throw new ApiException('数据不存在', 1);
        }
        adminLog($grid, AdminActionTypeEnum::DELETE, '删除网格');
        $grid->delete();
        return true;
    }
}
